﻿using JNPF.Basics.Logic;
using JNPF.Basics.Models;
using JNPF.Utils;
using log4net;
using Microsoft.AspNetCore.Builder;
using System;

namespace JNPF.Extensions.Middlewares
{
    /// <summary>
    /// Quartz 启动服务
    /// </summary>
    public static class QuartzJobMildd
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(QuartzJobMildd));
        public static void UseQuartzJobMildd(this IApplicationBuilder app, TimeTaskIService timeTaskIService, CronUtil cronUtil)
        {
            if (app == null) throw new ArgumentNullException(nameof(app));

            try
            {
                //if (Appsettings.app("Middleware", "QuartzNetJob", "Enabled").ObjToBool())
                //{

                var allQzServices = timeTaskIService.GetList().Result;
                foreach (var item in allQzServices)
                {
                    if (item.EnabledMark == 1)
                    {
                        var model = JsonHelper.ToObject<ContentModel>(item.ExecuteContent);
                        cronUtil.StartJobAsync(item, model, "");

                    }
                }

                //}
            }
            catch (Exception e)
            {
                log.Error($"An error was reported when starting the job service.\n{e.Message}");
                throw;
            }
        }
    }
}
